require File.join(File.dirname(__FILE__), "/../lib/rpm_packager")
include RpmPackager

desc 'build RPM package for Rails application'
task :rpm_package do
  fakeroot = File.join(RAILS_ROOT, '.fakeroot')
  rm_rf fakeroot
  dest_dir = File.join(fakeroot, 'usr', 'local', 'lib', 'rails-apps', app_name)
  mkdir_p dest_dir

  # TODO: maybe we should allow user to specify file filters
  Dir[File.join(RAILS_ROOT, "*")].each{|entry| cp_r entry, dest_dir unless (entry.index(".") == 0)}
  rm_svn dest_dir
  generate_spec_file
  replace_shebang File.join(dest_dir, "public", "dispatch.cgi")
  replace_shebang File.join(dest_dir, "public", "dispatch.rb")
  
  system "rpmbuild -bb --buildroot=#{fakeroot} #{app_name}.spec"
  unless $? == 0
    puts "\nWARNING: CANNOT BUILD RPM"
    puts "You need install rpmbuild ('apt-get install rpmbuild' or 'yum install rpmbuild') and configure it before you can package your Rails application."
    puts "refer to 'http://genetikayos.com/code/repos/rpm-tutorial/trunk/rpm-tutorial.html' for infomation about rpmbuild configuration.\n\n"  
  end

  rm File.join(RAILS_ROOT, "#{app_name}.spec")
  rm_rf fakeroot  
end

# Following tasks are used after RPM installed.
desc 'Create a RubyWorks container for packaged application.'
task :create_container do
  haproxy_port = ENV['HAPROXY_PORT'].to_i
  start_port = ENV['START_PORT'].to_i
  if haproxy_port == 0 || start_port == 0
    puts "USAGE: rake create_container HAPROXY_PORT=<port> START_PORT=<port>"
    return
  end
  
  config_file = generate_container_config_file haproxy_port, start_port
  cd control_center do
    system "container/create_app_container.rb #{config_file}"
    rails_dest = File.join(control_center, "config", "sites", app_name, "web", "rails")
    rm_rf rails_dest
    ln_s File.expand_path(RAILS_ROOT), rails_dest
  end

#  Rake::Task[:start_container].invoke
end

desc 'Remove container from RubyWorks rails-control-center'
task :remove_container => [:stop_container] do
  cd control_center do 
    rm_rf "config/sites/#{app_name}"
    rm_rf "ddis/#{app_name}"
  end
end

desc 'Start application container'
task :start_container do
  cd control_center do 
    system "container/site_controller.rb start #{app_name}" # TODO: now we start only one mongrel instance
  end  
end

desc 'Stop application container'
task :stop_container do
  cd control_center do 
    system "container/site_controller.rb stop #{app_name}"
  end  
end

private
def control_center
  "/usr/local/lib/rails-control-center" # TODO: do we need some way to config this?
end
